﻿using Commons.ReturnData;
using OpenAI.Domain.Entities;
using OpenAI.Domain.IRepositories;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAI.Infrastructure.Repositories
{
    public class ChatMessageRepository : IChatMessageRepository
    {
        private readonly ChatDbContext context;

        public ChatMessageRepository(ChatDbContext context)
        {
            this.context = context;
        }

        public async Task<SingleResult> DeleteChatMessageAsync(int id, Guid appUserId)
        {
            var mes = await context.ChatMessages.Include(x=>x.ChatSession).FirstOrDefaultAsync(x=>x.Id == id &&x.ChatSession.AppUserId == appUserId);
            if (mes != null)
            {
                mes.SoftDelete();
                context.ChatMessages.Update(mes);
                await context.SaveChangesAsync();
                return new SingleResult(true);
            }
            else
            {
                return new SingleResult(false);
            }
        }

        public async Task<DataResult<ChatMessage>> GetChatMessagesAsync(int pageSize, int chatSessionId)
        {
            var ret = new DataResult<ChatMessage>();
            if (pageSize <= 0)
            {
                pageSize = 100;
            }
            var datas = await context.ChatMessages.Include(x=>x.ChatSession).Where(x=>x.ChatSession.Id == chatSessionId).OrderByDescending(x=>x.CreationTime).Take(pageSize).ToListAsync();
            ret.Datas = datas.OrderBy(x=>x.CreationTime).ToList();
            return ret;
        }

        public async Task<SingleResult> SendChatMessageAsync(ChatMessage chatMessage)
        {
            try
            {
                await context.ChatMessages.AddAsync(chatMessage);
                await context.SaveChangesAsync();
                return new  SingleResult(true);
            }
            catch (Exception e)
            {

                throw;
            }
        }
    }
}
